package com.ww.scm.valueObject;

import com.ww.scm.entity.pub.Sequence;
import com.ww.scm.repository.pub.SequenceRepository;

public class SequenceVo {

	private String key;
	private int poolSize;
	private int valueMax;
	private int valueMin;
	private int nextValue;
	
	public SequenceVo(String key,int poolSize,SequenceRepository sequenceRepository) {
		this.key=key;
		this.poolSize=poolSize;
		Sequence sequence=sequenceRepository.findUniqueBy("key", key);
		if (sequence==null){
			sequence=new Sequence(key);
		}
		valueMin=sequence.getValue();
		sequence.addValue(poolSize);
		valueMax=sequence.getValue();
		nextValue=valueMin;
		
		sequenceRepository.save(sequence);
	}

	public SequenceVo(String key,int poolSize,int nextValue, int valueMin, int valueMax) {
		this.key=key;
		this.poolSize=poolSize;
		this.nextValue = nextValue;
		this.valueMin = valueMin;
		this.valueMax = valueMax;
	}


	public int getNextValue(SequenceRepository sequenceRepository) {
		if (nextValue>valueMax){
			Sequence sequence=sequenceRepository.findUniqueBy("key", key);
			//valueMin=sequence.getValue()+1;
			sequence.addValue(poolSize);
			valueMax=sequence.getValue();
			//nextValue=valueMin;
			sequenceRepository.save(sequence);
		}
		return nextValue++;
	}
}
